package jvm.c2_classloader;

import jvm.Hello;
import jvm.MyHello;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

public class T006_MSBClassLoader extends ClassLoader {

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        System.out.println("-------------");

        File f = new File("d:/jvmTest/", name.replace(".", "/").concat(".class"));
        try {
            FileInputStream fis = new FileInputStream(f);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int b = 0;

            while ((b=fis.read()) !=-1) {
                baos.write(b);

            }

            byte[] bytes = baos.toByteArray();//加载字节码文件到内存中
            baos.close();
            fis.close();//可以写的更加严谨

            return defineClass(name, bytes, 0, bytes.length);
        } catch (Exception e) {
//            e.printStackTrace();
            System.out.println("lll");
        }
        return super.findClass(name); //throws ClassNotFoundException
    }

    public static void main(String[] args) throws Exception {
        ClassLoader l = new T006_MSBClassLoader();
        Class clazz = l.loadClass("jvm.xff.Hello");
//        Class clazz1 = l.loadClass("com.mashibing.jvm.Hello");

//        System.out.println(clazz == clazz1);

//        Hello h = (Hello)clazz.newInstance();
//        h.m();
        MyHello hello = (MyHello) clazz.newInstance();

        System.out.println(hello);
        System.out.println(l.getClass().getClassLoader());
        System.out.println(l.getParent());

        System.out.println(getSystemClassLoader());
    }
}
